const api = require('../../../../ws_micro_shop/utils/api.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');

const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

Page({
  data: {
    cid: -1,
    scrollLeft: 600,
    scrollTop: 0,
    emptyGoods: 0,
    page_count: 0,
    classa: (app.tabbarindex === 0 ? false : true) || app.siteInfo.tabbar_type === '2',
    attachment_url: app.siteInfo.attachment_url,
    theme: app.themeData,
    unit: '',
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    isSwitchOn: false,
    abnorData: {
      imgSrc: app.imgUrl + 'goods_empty.png',
      text: '暂无拼团商品',
    },
    imgUrl: app.imgUrl,
    isShowLoading: false,
  },
  onLoad(opts) {
    let options = opts || {};
    this.setData({
      orgPrice: app.ws_micro_shop_globalData.orgPrice,
      useTabbar: this.data.useTabbar && app.getTabBarStatus(),
    })
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    app.pageOnLoad(this);
    let userinfo = wx.getStorageSync('user_info');
    let store = wx.getStorageSync('store');
    let that = this;
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
    }
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    let sessionFormStr = {
      shop_id: app.ws_micro_shop_globalData.shopid,
    };
    let serviceMessageTitle = '';
    let serviceMessagePath = 'index';

    if (userinfo && store) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      this.setData({
        store,
      });
      util.prepareBindInfo(options, moduleName, that);
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
        app.getStoreData().then(res => {
          store = wx.getStorageSync('store');
          that.setData(
            store,
          );
        });
      });
    }
    this.systemInfo = wx.systemInfo;
    this.loadIndexInfo(this);
    options.cid && this.loadGoodsList(options.cid);
    this.setData({
      opts: options,
      cid: options.cid || -1,
      sessionFormStr: JSON.stringify(sessionFormStr),
      serviceMessagePath,
      serviceMessageTitle,
      showtoindex: app.isSinglePage(this.route, getCurrentPages().length),
    });

  },
  onHide() {
    util.sendBindInfo(this.data);
  },
  onUnload() {
    util.sendBindInfo(this.data);
  },
  onShareAppMessage() {
    let path = '/ws_micro_shop_pt/pages/pt/index/index?tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid;
    path = app.util.spliceSharePath(path, '4', moduleName);
    return {
      path,
    };
  },
  onShareTimeline() {
    return {
      title: '',
      imageUrl: '',
      query: 'tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid
    }
  },
  loadIndexInfo(e) {
    let _this = e;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.index,
      method: 'GET',
      success: function (res) {
        if (res.code === 0) {
          setTimeout(function () {
            wx.hideLoading();
          }, 1000);
          let bannerList = res.data.banner;
          let adList = res.data.ad;
          _this.wxAppParams(bannerList, 'page_url');
          _this.wxAppParams(adList, 'url');
          _this.setData({
            cat: res.data.cat,
            banner: bannerList,
            ad: adList,
            page: res.data.goods.page,
            page_count: res.data.goods.page_count,
          });
          if (!_this.options.cid) {
            _this.setData({
              goods: res.data.goods.list || [],
            });
          }
          if (res.data.goods.row_count <= 0) {
            _this.setData({
              emptyGoods: 1,
            });
          }
        }
      },
      complete: function() {
        _this.setData({
          isShowLoading: true,
        });
      }
    });
  },
  switchNav(e) {
    let id = Number(e.currentTarget.dataset.id);
    let cid = this.data.cid;
    if (cid === id) return;
    cid = id;
    let windowWidth = this.systemInfo.windowWidth;
    let offsetLeft = e.currentTarget.offsetLeft;
    let scrollLeft = this.data.scrollLeft;
    if (offsetLeft > windowWidth / 2) {
      scrollLeft = offsetLeft;
    } else {
      scrollLeft = 0;
    }
    this.setData({
      cid,
      page: 1,
      scrollLeft,
      scrollTop: 0,
      emptyGoods: 0,
      goods: [],
      show_loading_bar: 1,
      isShowLoading: false,
    });
    this.loadGoodsList(cid);
  },
  loadGoodsList(id) {
    let _this = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.list,
      method: 'GET',
      data: {
        cid: id,
      },
      success: function (res) {
        if (res.code === 0) {
          let goods = res.data.list || [];
          if (res.data.page_count >= res.data.page) {
            _this.setData({
              goods,
              page: res.data.page,
              page_count: res.data.page_count,
              row_count: res.data.row_count,
              show_loading_bar: 0,
            });
          } else {
            _this.setData({
              emptyGoods: 1,
            });
          }
        }
      },
      complete: function () {
        wx.hideLoading();
        _this.setData({
          isShowLoading: true,
        });
      }
    });
  },
  pullDownLoading(e) {
    let _this = this;
    if (Number(_this.data.emptyGoods) === 1 || Number(_this.data.show_loading_bar) === 1) {
      return;
    }
    _this.setData({
      show_loading_bar: 1,
    });
    let pageNum = parseInt(_this.data.page + 1, 10);
    let cid = _this.data.cid;
    app.ws_micro_shoprequest({
      url: api.group.list,
      method: 'GET',
      data: {
        page: pageNum,
        cid,
      },
      success: function (res) {
        if (res.code === 0) {
          let goods = _this.data.goods;
          if (res.data.page > _this.data.page) {
            Array.prototype.push.apply(goods, res.data.list);
          }
          if (res.data.page_count >= res.data.page) {
            _this.setData({
              goods,
              page: res.data.page,
              page_count: res.data.page_count,
              row_count: res.data.row_count,
              show_loading_bar: 0,
              isShowLoading: true,
            });
          } else {
            _this.setData({
              emptyGoods: 1,
            });
          }
        }
      },
    });
  },
  navigatorClick(e) {
    let param = e.currentTarget.dataset;
    let open_type = param.open_type;
    let pageUrl = param.url || '';
    if (open_type === 'wxapp') {
      let urlParams = param.urlParams || '';
      let close = param.close || '';
      app.util.navigateTo(pageUrl, urlParams, close);
    }
    if (open_type !== 'wxapp') {
      return true;
    }
    let url = this.parseQueryString(pageUrl);
    url.path = url.path ? decodeURIComponent(url.path) : '';
    wx.navigateToMiniProgram({
      appId: url.appId,
      path: url.path,
    });
    return false;
  },
  parseQueryString(url) {
    let reg_url = /^[^\?]+\?([\w\W]+)$/;
    let reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g;
    let arr_url = reg_url.exec(url);
    let ret = {};
    if (arr_url && arr_url[1]) {
      let str_para = arr_url[1];
      let result;
      while ((result = reg_para.exec(str_para)) != null) {
        ret[result[1]] = result[2];
      }
    }
    return ret;
  },
  wxAppParams(list, str) {
    if (list && list.length > 0) {
      for (let i in list) {
        if (list[i].open_type === 'wxapp') {
          list[i].appData = this.parseQueryString(decodeURIComponent(list[i][str]));
        }
      }
      // 内部模块的正则筛选
      let RegExp = /^\/pages/;
      for (let item of list) {
        if (RegExp.test(item[str])) {
          if (item[str].indexOf('/book/') > 0) {
            item[str] = `/ws_micro_shop_book${item[str]}`;
          } else if (item[str].indexOf('/pt/') > 0) {
            item[str] = `/ws_micro_shop_pt${item[str]}`;
          } else if (item[str].indexOf('/miaosha/') > 0) {
            item[str] = `/ws_micro_shop_ms${item[str]}`;
          } else {
            item[str] = `/ws_micro_shop${item[str]}`;
          }
        }
      }
    }
  },
  to_dial() {
    let contact_tel = this.data.store.contact_tel;
    wx.makePhoneCall({
      phoneNumber: contact_tel,
    });
  },
  onNavigate(e) {
    let param = e.currentTarget.dataset;
    app.ws_micro_shop_navigate(param);
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
  tabMiniCard(e) {
    let args = e.detail;
    let currentPath = '';
    let pages = getCurrentPages();
    pages.length > 0 && (currentPath = '/' + pages.pop().route);
    currentPath !== args.path
      && setTimeout(() => {
        app.util.navigateTo(args.path, args.query);
      }, 500);
  },
  switchTap() {
    let { isSwitchOn } = this.data;
    this.setData({ isSwitchOn: !isSwitchOn });
  },
});
